package com.aidex.biz.controller;

import com.aidex.biz.domain.Customer;
import com.aidex.biz.domain.CustomerDongtai;
import com.aidex.biz.domain.ToHome;
import com.aidex.biz.domain.ToHomeUser;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.biz.service.CustomerDongtaiService;
import com.aidex.biz.service.CustomerService;
import com.aidex.biz.service.ToHomeService;
import com.aidex.biz.service.ToHomeUserService;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 上门接待人员Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-11-23
 */
@RestController
@RequestMapping("/biz/bizToHomeUser")
public class ToHomeUserController extends BaseController {
    @Autowired
    private ToHomeUserService toHomeUserService;
    @Autowired
    private ToHomeService toHomeService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private MessageSendService messageSendService;

    /**
     * 查询上门接待人员列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:list')")
    @GetMapping("/list")
    public R<PageInfo> list(ToHomeUser toHomeUser, HttpServletRequest request, HttpServletResponse response) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            toHomeUser.setCompanyId(null);
        } else {
            toHomeUser.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        toHomeUser.setPage(new PageDomain(request, response));
        return R.data(toHomeUserService.findPage(toHomeUser));
    }

    /**
     * 查询方案沟通列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:list')")
    @GetMapping("/listFangAnGouTong")
    public R<PageInfo> listFangAnGouTong(ToHomeUser toHomeUser, HttpServletRequest request, HttpServletResponse response) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            toHomeUser.setCompanyId(null);
        } else {
            toHomeUser.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        toHomeUser.setPage(new PageDomain(request, response));
        return R.data(toHomeUserService.findPageFangangoutong(toHomeUser));
    }


    /**
     * 获取上门接待人员详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:query')")
    @GetMapping(value = "/{id}")
    public R<ToHomeUser> detail(@PathVariable("id") String id) {
        return R.data(toHomeUserService.get(id));
    }

    /**
     * 客户到店-方案沟通
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:add')")
    @Log(title = "上门接待人员", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated ToHomeUser toHomeUser) {
        if (toHomeUser.getQdUsers().length == 0) {
            return R.fail("请选择用户");
        }
        for (SysUser user : toHomeUser.getQdUsers()) {
            toHomeUser.setId(UUID.randomUUID().toString());
            toHomeUser.setIsNewRecord();
            toHomeUser.setDName(user.getDeptName());
            toHomeUser.setUName(user.getUserName());
            toHomeUser.setUserId(user.getUserId());
            toHomeUser.setDeptId(user.getDeptId());
            toHomeUser.setUserName(user.getUserName());
            toHomeUser.setDeptName(user.getDeptName());
            toHomeUser.setStatus(CustomerEnum.CUS_TO_HM.getStatus());
            toHomeUser.setYushenStatus("0"); // 待预审
            toHomeUser.setCustomerId(toHomeUser.getCustomerId());
            toHomeUserService.save(toHomeUser);
        }
        ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
        toHome.setToHomeTime(new Date());
        toHome.setStatus("1");
        if (!StringUtils.isEmpty(toHome.getCustomerId())) {
            Customer customer = customerService.get(toHome.getCustomerId());
            customer.setBusinessStatus(CustomerEnum.CUS_TO_HM.getStatus());
            customerService.save(customer);
        }

        return R.status(toHomeService.save(toHome));

    }

    /**
     * 修改上门接待人员
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:edit')")
    @Log(title = "上门接待人员", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated ToHomeUser toHomeUser) {
        return R.status(toHomeUserService.save(toHomeUser));
    }


    /**
     * 谈单经理接单
     */
    @Log(title = "谈单经理接单", businessType = BusinessType.UPDATE)
    @PostMapping("/jiedan")
    public R jiedan(@RequestBody @Validated ToHomeUser toHomeUser) {
        Customer customer = customerService.get(toHomeUser.getCustomerId());
        customer.setBusinessStatus(toHomeUser.getStatus());

        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (null != currentUser) {
            toHomeUser.setUserName(currentUser.getUserName());
            toHomeUser.setUserId(currentUser.getId());
            toHomeUser.setDeptId(currentUser.getDeptId());
            toHomeUser.setDeptName(currentUser.getDeptName());
            // 谈单经理接单
            toHomeUser.setTandanUserId(currentUser.getId());
            toHomeUser.setTandanUserName(currentUser.getName());
        }


        ToHome toHome = toHomeService.get(toHomeUser.getTohomeId());
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(toHomeUser.getCustomerId());
        customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-接单");
        customerDongtaiService.save(customerDongtai);
        // 谈单经理接单@所有人
        String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String toHomeCompanyId = toHome.getToHomeCompanyId();
        if (StringUtils.isNull(toHomeCompanyId) || StringUtils.isEmpty(toHomeCompanyId)) {
            toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        }
        messageSendService.sendJinjianVxNewsToCompany(null, "销售接单", new String[]{customer.getCusName(), currentUser.getName(), toHome.getMeetingRoom(), sdf}, toHomeCompanyId);
        return R.status(toHomeUserService.save(toHomeUser) && customerService.save(customer));
    }

    /**
     * 删除上门接待人员
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:remove')")
    @Log(title = "上门接待人员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(toHomeUserService.deleteToHomeUserByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:query')")
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(toHomeUserService.findMaxSort(new ToHomeUser()));
    }

    /**
     * 导出上门接待人员列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizToHomeUser:export')")
    @Log(title = "上门接待人员", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(ToHomeUser toHomeUser) {

        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            toHomeUser.setCompanyId(null);
        } else {
            toHomeUser.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<ToHomeUser> list = toHomeUserService.findList(toHomeUser);
        ExcelUtil<ToHomeUser> util = new ExcelUtil<ToHomeUser>(ToHomeUser.class);
        return util.exportExcel(list, "上门接待人员数据");
    }

}
